﻿using System;
using Game.Foundation;
using Bruce.Net;

namespace Server.Game.Generic
{
    public class Player
    {
        public ISession Session { get; private set; }

        public AbsGameGroup Group { get; set; }

        public byte SeatIndex { get; set; }

        public string UserName
        {
            get;
            private set;
        }

        private GameStatus _status;

        public GameStatus Status
        {
            get
            {
                return this._status;
            }
            set
            {
                if (this._status == value) return;

                this._status = value;
                OnStatusChanged(value);
                switch (value)
                {
                    case GameStatus.Ready:
                        this.Group.TryStart();
                        break;
                    case GameStatus.Absent:
                        this.Group[this.SeatIndex] = null;
                        break;
                }
            }
        }

        public Player(string name, ISession session)
        {
            if (session == null) throw new ArgumentNullException("session");

            this.UserName = name;
            this.Session = session;
            this.Session.SetRelationData<Player>(this);
        }

        public void SendMessage(IPacket packet)
        {
            this.Session.SendAsync(packet);
        }

        private void OnStatusChanged(GameStatus type)
        {
            Packet p = new Packet((int)PacketType.分组列表改变通知包);
            p.OptionOne = (byte)type;
            p.WriteInt32(this.Group.ID);
            p.WriteByte(this.SeatIndex);
            p.WriteString(this.UserName);

            this.Group.Room.SendToAll(p);
        }
    }
}
